﻿using Microsoft.Data.SqlClient;
using Quartz;
using XJay.Identity.Common.Helper;

namespace XJIE.Schedule.Common.Helper
{
    public static class LogHelper
    {
        public static async Task InfoAsync(this IJobExecutionContext jobContext!!, string message!!)
        {
            await AddLogAsync(jobContext.JobDetail.Key.Group, jobContext.JobDetail.Key.Name,message);
        }

        public static async Task ErrorAsync(this IJobExecutionContext jobContext!!, string message!!)
        {
            await AddLogAsync(jobContext.JobDetail.Key.Group, jobContext.JobDetail.Key.Name, message, "Error");
        }

        public static void Info(this IJobExecutionContext jobContext!!, string message!!)
        {
            AddLogAsync(jobContext.JobDetail.Key.Group, jobContext.JobDetail.Key.Name, message).Wait();
        }

        public static void Error(this IJobExecutionContext jobContext!!, string message!!)
        {
            AddLogAsync(jobContext.JobDetail.Key.Group, jobContext.JobDetail.Key.Name, message, "Error").Wait();
        }

        private static async Task AddLogAsync(string group,string name,string msg,string logtype = "Info")
        {
            using (var connection = new SqlConnection(AppConfig.ConnectionString))
            {
                await connection.OpenAsync();
                var sql = @$"INSERT INTO [dbo].[App_JobLog]
                               ([LogType]
                               ,[Message]
                               ,[JobGroup]
                               ,[JobName])
                         VALUES
                               ('{logtype}'
                               ,'{msg}'
                               ,'{group}'
                               ,'{name}'
                        )";

                SqlCommand sqlCommand = new SqlCommand(sql, connection);
                await sqlCommand.ExecuteNonQueryAsync();
                await connection.CloseAsync();
            }
        }
    }
}
